package com.example.his.api.mis.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.example.his.api.common.PageUtils;
import com.example.his.api.common.R;
import com.example.his.api.mis.controller.form.order.CheckPaymentResultForm;
import com.example.his.api.mis.controller.form.order.DeleteOrderByIdForm;
import com.example.his.api.mis.controller.form.order.SearchOrderByPageForm;
import com.example.his.api.mis.controller.form.order.UpdateOrderRefundStatusById;
import com.example.his.api.mis.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;

@RestController("MisOrderController")
@RequestMapping("/mis/order")
public class OrderController {
  
  @Resource
  private OrderService orderService;
  
  //  根据条件搜索订单列表
  @PostMapping("/searchByPage")
  @SaCheckPermission(value = { "ROOT", "ORDER:SELECT" }, mode = SaMode.OR)
  public R searchByPage(@RequestBody @Valid SearchOrderByPageForm form) {
    if(form.getStartDate() != null && form.getEndDate() != null) {
      DateTime startDate = DateUtil.parse(form.getStartDate());
      DateTime endDate = DateUtil.parse(form.getEndDate());
      if(startDate.isAfter(endDate)) {
        return R.error("开始日期不能大于结束日期");
      }
    }
    int page = form.getPage();
    int length = form.getLength();
    int start = (page - 1) * length;
    Map param = BeanUtil.beanToMap(form);
    param.put("start", start);
    PageUtils pageUtils = orderService.searchByPage(param);
    return R.ok().put("result", pageUtils);
  }
  
  //  同步付款结果
  @PostMapping("/checkPaymentResult")
  @SaCheckPermission(value = { "ROOT", "ORDER:UPDATE" }, mode = SaMode.OR)
  public R checkPaymentResult(@RequestBody @Valid CheckPaymentResultForm form) {
    int rows = orderService.checkPaymentResult(form.getOutTradeNoArray());
    return R.ok().put("result", rows);
  }
  
  //  删除已关闭的订单
  @PostMapping("/deleteById")
  @SaCheckPermission(value = { "ROOT", "ORDER:DELETE", }, mode = SaMode.OR)
  public R deleteById(@RequestBody @Valid DeleteOrderByIdForm form) {
    boolean b = orderService.deleteById(form.getId());
    return R.ok().put("result", b);
  }
  
  //  线下退款修改订单状态
  @PostMapping("/updateRefundStatusById")
  @SaCheckPermission(value = { "ROOT", "ORDER:UPDATE" }, mode = SaMode.OR)
  public R updateRefundStatusById(@RequestBody @Valid UpdateOrderRefundStatusById form) {
    boolean b = orderService.updateRefundStatusById(form.getId());
    return R.ok().put("result", b);
  }
  
  
}
